package com.webdemo05.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.webdemo05.pojo.User;
import com.webdemo05.util.HibernateHandler;

public class UpdateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public UpdateUser() {
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String flag = request.getParameter("flag");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		Session session = HibernateHandler.newInstance().getCurrentSession();
		if ("update".equals(flag)) {
			User user = new User();
			user.setId(Integer.parseInt(id));
			user.setName(name);
			session.beginTransaction();
			session.update(user);
			session.getTransaction().commit();
			response.sendRedirect(this.getServletContext().getContextPath()+"/QueryUser");
		} else {
			session.beginTransaction();
			User user = (User) session.load(User.class, Integer.parseInt(id));
			session.getTransaction().commit();
			request.setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
		}
	}
}
